package com.itguigu.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.text.AttributedString;
import java.util.UUID;

@Controller
public class LoginController {
    @Autowired
    private StringRedisTemplate restTemplate;

    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_url") String redirect, Model model, @CookieValue(value = "sso_token", required = false) String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) {
            return "redirect:" + redirect + "?token=" + sso_token;
        }
        model.addAttribute("url", redirect);


        return "login";

    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password,
                          @RequestParam("url") String url, HttpServletResponse response) {
        //登陆成功 跳转
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            //登录成功  跳回之前的页面
            //登陆成功的用户存到redis
            String uuid = UUID.randomUUID().toString().replace("-", "");
            restTemplate.opsForValue().set(uuid, username);
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);
            return "redirect:" + url + "?token=" + uuid;
        }
//失败    登录
        return "login";

    }
}
